package com.cari.oa.controller;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.validation.Valid;

import org.springframework.beans.propertyeditors.CustomDateEditor;
import org.springframework.beans.propertyeditors.StringTrimmerEditor;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.InitBinder;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.SessionAttributes;

import com.cari.oa.domain.AttachmentEntity;
import com.cari.oa.domain.CommentEntity;
import com.cari.oa.domain.MarketProjectEntity;
import com.cari.oa.domain.NotificationEntity;
import com.cari.oa.domain.ReqEntity;
import com.cari.oa.domain.ReqTypeEntity;
import com.cari.oa.domain.ReqUserRefEntity;
import com.cari.oa.domain.SysDictItemEntity;
import com.cari.oa.service.AttachmentService;
import com.cari.oa.service.CommentService;
import com.cari.oa.service.MarketProjectService;
import com.cari.oa.service.NotificationService;
import com.cari.oa.service.ReqService;
import com.cari.oa.service.ReqTypeService;
import com.cari.oa.service.ReqUserRefService;
import com.cari.oa.service.SysDictItemService;
import com.cari.oa.service.SysUserService;
import com.cari.oa.util.Contants;
import com.cari.oa.util.StrUtils;
import com.cari.oa.util.Utils;

/**
* Title: ReqController
* Description:需求control
* Company:   cari 
* @author    hjx 
* @date      2013-3-12
*/
@Controller
@SessionAttributes({"username","usercnname"})
public class DepReqController extends BaseDownloadController {

	@Resource
	private ReqService reqService;
	@Resource
	private SysUserService sysUserService;
	@Resource
	private SysDictItemService sysDictItemService;
	@Resource
	private ReqTypeService reqTypeService;
	@Resource
	private CommentService commentService;
	@Resource
	private AttachmentService attachmentService;
	@Resource
	private ReqUserRefService reqUserRefService;
	@Resource
    private MarketProjectService marketProjectService;
	@Resource
	private NotificationService notificationService;
	
	public static final String MODULE_NAME = "REQ_MANAGE";
	
    @InitBinder
    public void initBinder(WebDataBinder binder) {
        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        binder.registerCustomEditor(Date.class, new CustomDateEditor(df, false));
        binder.registerCustomEditor(String.class, new StringTrimmerEditor(true));
    }
	/**
	* Title: list
	* Description:分页查询需求数据
	* @author    hjx 
	* @date       2013-3-13 
	* @param title     标题
	* @param initiator 发起人
	* @param status    状态
	* @param reqType   需求类型
	* @param curPage
	* @param modelMap
	* @return
	*/
    @RequestMapping("depreq/list.do")
    public String list(@ModelAttribute("username") String username, String title, 
    		String cnName, String sortType,  
    		String status, String reqType,
    		String project, String pName, 
    		Integer curPage, ModelMap modelMap) {
       
    	if(curPage == null) curPage = 1;
        ReqUserRefEntity ruf = reqUserRefService.getByEnname(username);
        reqType = ruf.getTypeId();
        List<MarketProjectEntity> projects = marketProjectService.getAll();
    	//if(StrUtils.isEmpty(project) && projects !=null && projects.size()>0){
    	//	pName = projects.get(0).getName();
    	//	project = projects.get(0).getId();
    	//}
    	long totalRecords = reqService.getCount(title, null, cnName, status, reqType, sortType, project);
        long totalPage = totalRecords / Contants.PAGE_SIZE + (totalRecords % Contants.PAGE_SIZE != 0 ? 1 : 0);
        
        List<ReqEntity> reqList = reqService.getPage(title, null, cnName, status, reqType, sortType, project, curPage, Contants.PAGE_SIZE);
        List<SysDictItemEntity> statusList = sysDictItemService.getItemsByGroupName("reqStatus");
        List<Map<String,String>> typeList = reqTypeService.getReqTypeNameAndPerson();
    	List<SysDictItemEntity> itemList =   sysDictItemService.getItemsByGroupName("reqStatus");
    	List<SysDictItemEntity> sList =   sysDictItemService.getItemsByGroupName("reqResponsible"); 

    	for(ReqEntity cur : reqList)
	    {
	      	for(Map<String,String> map : typeList)
	      	{
	      		if(StrUtils.isNotEmpty(cur.getReqType()) && cur.getReqType().equals(map.get("typeId")))
	      		{   
	      			if(StrUtils.isEmpty(cur.getPrincipal())){
	        			cur.setTypeName(map.get("typeName"));
	        			cur.setPrincipal(map.get("cnName"));
	      			}else
	      			{
	      				cur.setPrincipal(cur.getPrincipal()+","+map.get("cnName"));
	      			}
	      		}
	      	}
	    }
    	
        modelMap.addAttribute("sList", sList);
        modelMap.addAttribute("projects", projects);
        modelMap.addAttribute("itemList", itemList);
        modelMap.addAttribute("typeList", typeList);
        modelMap.addAttribute("statusList", statusList);
        modelMap.addAttribute("reqList", reqList);
        modelMap.addAttribute("curPage", curPage);
        modelMap.addAttribute("totalPage", totalPage);
        modelMap.addAttribute("totalRecords", totalRecords);
        modelMap.addAttribute("title", title);
        modelMap.addAttribute("cnName", cnName);
        modelMap.addAttribute("status", status);
        modelMap.addAttribute("reqType", reqType);
        modelMap.addAttribute("sortType", sortType);
        modelMap.addAttribute("project", project);
        modelMap.addAttribute("pName", pName);

        return "req/depreq/list";
    }
    
    /**
     * Title: enterView
     * Description:查看页面
     * @author     hjx 
     * @date       2013-3-13 
     * @param id
     * @param modelMap
     * @return
     */
     @RequestMapping(value = "depreq/view.do", method = RequestMethod.GET)
     public String enterView(String id,String qs, ModelMap modelMap) {
     	ReqEntity req = reqService.getById(id);
     	List<AttachmentEntity> attList = attachmentService.getByObjectId(id);
     	List<CommentEntity> comList = commentService.getListByObjID(id,CommentService.CMT_REQ);
     	List<SysDictItemEntity> itemList = sysDictItemService.getItemsByGroupName("reqStatus"); 
     	List<SysDictItemEntity> sList = sysDictItemService.getItemsByGroupName("reqResponsible"); 
        modelMap.addAttribute("sList", sList);
     	modelMap.addAttribute("itemList", itemList);
	    modelMap.addAttribute("comList", comList);
	    modelMap.addAttribute("attList", attList);
	    modelMap.addAttribute("req", req);
        List<ReqTypeEntity> typeList = reqTypeService.getAll();
        modelMap.addAttribute("typeList", typeList);
        modelMap.addAttribute("qs", qs);
        ReqUserRefEntity ruf = reqUserRefService.getByReqType(req.getReqType());
        modelMap.addAttribute("principal", sysUserService.getByEnname(ruf.getEnname()).getCnname());
	    return "req/depreq/view";
     }
     
    /**
 	* Title: enterEdit
 	* Description:进入修改页面
 	* @author    hjx 
 	* @date       2013-3-13 
 	* @param id
 	* @param qs
 	* @param modelMap
 	* @return
 	*/
     @RequestMapping(value = "depreq/edit.do", method = RequestMethod.GET)
     public String enterEdit(String id, String qs, ModelMap modelMap) {
     	ReqEntity req = reqService.getById(id);
     	List<AttachmentEntity> attList = attachmentService.getByObjectId(id);
     	List<CommentEntity> comList = commentService.getListByObjID(id,CommentService.CMT_REQ);
     	List<SysDictItemEntity> itemList = sysDictItemService.getItemsByGroupName("reqStatus"); 
     	List<SysDictItemEntity> sList =  sysDictItemService.getItemsByGroupName("reqResponsible"); 
        modelMap.addAttribute("sList", sList);
     	modelMap.addAttribute("itemList", itemList);
        modelMap.addAttribute("comList", comList);
     	modelMap.addAttribute("attList", attList);
        modelMap.addAttribute("req", req);
        modelMap.addAttribute("qs", qs);
        return "req/depreq/edit";
     }
     
     /**
      * Title: postEdit
      * Description:处理情况
      * @author     hjx 
      * @date       2013-3-13 
      * @param username
      * @param req
      * @param result
      * @return
      */
      @RequestMapping(value = "depreq/edit.do", method = RequestMethod.POST)
      @ResponseBody
      public String postEdit(@ModelAttribute("username") String username,@ModelAttribute("usercnname") String usercnname, Date perEndTime,Date perStaTime, String reason,String status,String id, @Valid ReqEntity req, BindingResult result) {
    	  req = reqService.getById(id);
          req.setStatus(status);
          NotificationEntity noti = null;
          if(status.equals("processing"))
          {   req.setPerStaTime(perStaTime);
              req.setPerEndTime(perEndTime);
        	  req.setInHangDesc(reason);
              noti = new NotificationEntity(req.getTitle()+"已进入处理中", req.getTitle()+"已进入处理中", username, usercnname, req.getInitiator(),req.getCnName(), 1);
          	 
          }else if(status.equals("refused"))
          {
              noti = new NotificationEntity(req.getTitle()+"已被拒绝", req.getTitle()+"已被拒绝", username, usercnname, req.getInitiator(),req.getCnName(), 1);
        	  req.setRefuseReason(reason);
          }
          else if(status.equals("processed"))
          {    
              noti = new NotificationEntity(req.getTitle()+"已处理完成", req.getTitle()+"已处理完成", username, usercnname, req.getInitiator(),req.getCnName(), 1);
        	  req.setPerStaTime(perStaTime);
              req.setPerEndTime(perEndTime);
        	  req.setFinishTime(new Date());
        	  req.setHandedDesc(reason);
          }
          reqService.update(req);
          notificationService.insert(noti);  //添加已被分发通知
          SysOperLogController.addOperLog(username, MODULE_NAME, "处理情况" + req.getTitle());
          return Utils.normalJsonResp();
      }
}
